<?php

/**
 * @ zuorenci
 * @ 2017-12-25
 */
namespace app\admin\controller\tuan;

use app\admin\model\User;
use app\common\controller\Backend;

use think\Cache;
use think\Controller;
use think\Request;
use think\Db;

/**
 * 
 *
 * @icon fa fa-circle-o
 */
class Ordertransactionrecord extends Backend
{
    
    /**
     * TuanOrder模型对象
     */
    protected $model = null;
    protected $order_type;
    protected $pay_type;
    protected $pay_status;
    protected $order_status;
    protected $searchFields = 'shop.shop_name';

    public function _initialize()
    {
        parent::_initialize();
        $this->model = model('TuanOrder');
        $this->order_type = [
            '1'=>'团购',
            '2'=>'买单',
            '3'=>'充值',
            '4'=>'现金支付'
        ];
        $this->pay_type = [
            '0'=>'未支付',
            '1'=>'余额支付',
            '2'=>'支付宝',
            '3'=>'微信支付',
            '4'=>'现金支付',
        ];
        $this->order_status = [//1待使用 2待评价 3已评价 4已取消 默认为0
            '0'=>'未支付',
            '1'=>'待使用',
            '2'=>'待评价',
            '3'=>'已评价',
            '4'=>'已取消',
        ];
        $this->pay_status = [
            2   =>  '已支付',
            1   =>  '未支付',
            -1  =>  '退款中',
            -2  =>  '已退款'
        ];

    }
    
    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个方法
     * 因此在当前控制器中可不用编写增删改查的代码,如果需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */
    

    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax())
        {
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $where1 = [
                'pay_type'      =>  ['gt',0],
                'order_type'    =>  ['in',[1,2,4]],
                'pay_status'    =>  ['in',[-1,-2,2]]
            ];

            $field = 'order_id,user_id,total_price,price,settlement_price,refund_num,num,pay_status,order_num,order_type,pay_type,create_time,pay_time,update_time,order_status,shop_id,user_id,back_money,subtract,remittal,allowance';
            $total = $this->model
                    ->with('shop')
                    ->where($where)
                    ->where($where1)
                    ->order($sort, $order)
                    ->count();
                $list = $this->model
                    ->field($field)
                    ->with(['shop'=>function($query){
                        $query->withField('user_id,shop_name,tel,cate_id,province_id,city_id,area_id');
                    }])
                    ->where($where)
                    ->where($where1)
                    ->order($sort, $order)
                    ->limit($offset, $limit)
                    ->select();

            $industry_model = new \app\admin\model\Industry();
            $city_model = new \app\admin\model\City();
            /*$attract_model = new \app\admin\model\Attract();
            $selearnings_model = new \app\admin\model\Selearnings();*/
            $user_model = new User();
            foreach ($list as $key=>$value){
                $price_subtract = ($value['price']+$value['subtract']+$value['allowance']) / 100;
                if($value['shop']){
                    $industryID = $value->shop['cate_id'];
                    $list[$key]['industry'] = $industry_model->where('industryID',$industryID)->value('name');
                    $user = $user_model->where('userID',$value->shop['user_id'])->find();
                    $list[$key]['phone'] = $user['phone'];
                    $list[$key]['account'] = $user['account'];
                }
                $list[$key]['order_type'] = $this->order_type[$value['order_type']];
                $list[$key]['order_status'] = $this->order_status[$value['order_status']];
                //地区查询
                $province_id = $value->shop['province_id'];
                $city_id = $value->shop['city_id'];
                $area_id = $value->shop['area_id'];
                if ($province_id){
                    $city1 = $city_model->where('cityID',$province_id)->value('name');
                    if ($city_id){
                        $city2 = $city_model->where('cityID',$city_id)->value('name');
                        if ($area_id){
                            $city3 = $city_model->where('cityID',$area_id)->value('name');
                            $list[$key]['city'] = $city1.'-'.$city2.'-'.$city3;
                        }else{
                            $list[$key]['city'] = $city1.'-'.$city2;
                        }
                    }else{
                        $list[$key]['city'] = $city1;
                    }
                }
                //分润实际金额+服务税
                if ($value['pay_status']==2){
                    //服务税
                    $list[$key]['money4'] = number_format(($value['price']+$value['subtract']+$value['allowance']-$value['back_money']-$value['settlement_price'])/100,2);
                    /*//实际分润
                    $money1 = $selearnings_model->where('id',$value['order_id'])->column('selearningsID');
                    if ($money1){
                        $money2 = $attract_model->where('source','in',$money1)->sum('fees');
                        $list[$key]['money3'] = number_format($money2/100,2);
                    }else{
                        $list[$key]['money3'] = 0;
                    }*/
                }elseif($value['pay_status']==-1){
                    $list[$key]['money3'] = '无';
                    $list[$key]['money4'] = '无';
                }else{
                    if($value['refund_num'] == $value['num']){
                        $list[$key]['money3'] = '无';
                        $list[$key]['money4'] = '无';
                    }else{
                        //服务费额
                        $list[$key]['money4'] = number_format(($price_subtract-$value['settlement_price'])/100,2);
                        /*//实际分润
                        $money1 = $selearnings_model->where('id',$value['order_id'])->column('selearningsID');
                        if ($money1){
                            $money2 = $attract_model->where('source','in',$money1)->sum('fees');
                            //分润
                            $list[$key]['money3'] = number_format($money2/100,2);
                        }else{
                            $list[$key]['money3'] = 0;
                        }*/
                    }
                }
                if($list[$key]['order_type'] == '现金支付') {
                    $list[$key]['pay_type'] = '现金支付';
                    //服务费额
                    $list[$key]['money4'] = bcmul($price_subtract,$value['remittal'],0)/100;
                } else {
                    $list[$key]['pay_type'] = $this->pay_type[$value['pay_type']];
                }
                $list[$key]['pay_status'] = $this->pay_status[$value['pay_status']];
                //实付金额
                $list[$key]['price'] = number_format($value['price']/100,2);
                //订单金额
                $list[$key]['price_subtract'] = number_format($price_subtract,2);
            }

            $str1 = md5($this->request->get("filter", ''));
            if (Cache::get($str1) != false) {
                $sum = Cache::get($str1);
            } else {
                $sum = Db::name('tuan_order')
                    ->alias('tuan_order')
                    ->field('sum(price) as sum1,sum(subtract) as sum2,sum(allowance) as sum3')
                    ->join('dy_shop shop','tuan_order.shop_id = shop.shop_id')
                    ->where($where)
                    ->where($where1)
                    ->cache($str1,90)
                    ->select();
            }
            $price1 = bcdiv($sum[0]['sum1'],100,2);
            $sum = bcdiv($sum[0]['sum1']+$sum[0]['sum2']+$sum[0]['sum3'],100,2);
            $result = array("total" => $total, "rows" => $list, "extend"=>['transaction_price'=>$sum,'price'=>$price1]);

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function edit($ids = NULL)
    {
        $tuan_model = new \app\admin\model\Tuan();
        $user_model = new \app\admin\model\User();
        $shop_model = new \app\admin\model\Shop();
        $city_model = new \app\admin\model\City();
        $attract_model = new \app\admin\model\Attract();
        $selearnings_model = new \app\admin\model\Selearnings();
        $pay_type = $this->pay_type;
        $order_status = $this->order_status;
        $row = $this->model
            ->where('order_id',$ids)
            ->find();
        switch ($row['order_type']){
            case 1:
                $type = $tuan_model->where('tuan_id',$row['tuan_id'])->value('type');
                if ($type==1){
                    $row['order_type'] = '团购套餐';
                }else{
                    $row['order_type'] = '代金券';
                }
                $a = Db::name('tuan_code')->where('order_id',$row['order_id'])->count();
                $row['num1'] = $a?$a:0;
            if ($row['num1']>0){
                $code_list =  Db::name('tuan_code')->where(['is_used'=>1,'order_id'=>$row['order_id']])->order('used_time desc')->select();
                if($code_list){
                    $row['num2'] = count($code_list);
                    $row['used_time'] = date('Y-m-d H:i:s',$code_list[0]['used_time']);
                }else{
                    $row['num2'] = 0;
                    $row['used_time'] = '未消费';
                }
            }else{
                $row['num2'] = 0;
            }
                break;
            case 2:
                if ($row['price']==$row['total_price']){
                    $row['order_type'] = '买单';
                }else{
                    $row['order_type'] = '优惠买单';
                }
                $row['num1'] = 0;
                $row['num2'] = 1;
                $row['used_time'] = date('Y-m-d H:i:s',$row['update_time']);
                break;
            case 4:
                $row['order_type'] = '现金支付';
                $row['pay_type1']  = '现金支付';
                $row['used_time'] = date('Y-m-d H:i:s',$row['update_time']);
                break;
        }
        $c = Db::name('consume')->where(['ordernum'=>$row['order_num'],'source'=>12])->value('fees');
        $row['shouyi'] = $c ? number_format($c*$row['num2']/100,2) : 0;
        $row['pay_type'] = $pay_type[$row['pay_type']];
        $row['order_status'] = $order_status[$row['order_status']];
        //实付金额
        $row['price'] = number_format($row['price']/100,2,'.','');
        //立减金额
        $row['subtract'] = number_format(($row['subtract']+$row['allowance'])/100,2,'.','');
        //原价
        $row['total_price'] = number_format($row['total_price']/100,2,'.','');
        //交易金额
        $row['price_subtract'] = $row['price']+$row['subtract'];
        //优惠金额
        $row['jm_price'] = number_format(($row['total_price']-$row['price']),2,'.','');
        //折扣价
        $row['zk_price'] = number_format(($row['total_price']-$row['price']-$row['subtract']),2,'.','');

        //分润实际金额+分润
        //72
        if ($row['pay_status']==2 ){
            //实际分润
            $money1 = $selearnings_model->where('id',$row['order_id'])->value('selearningsID');
            if ($money1){
                $money2 = $attract_model->where('source','in',$money1)->sum('fees');
                if($money2){
                    if ($row['order_type'] ==1){
                        $row['money3'] = '￥'.($money2/100*$row['num2']);
                    }else{
                        $row['money3'] = '￥'.($money2/100);
                    }
                }else{
                    if(($row['price']+$row['subtract'] -$row['back_money']/100 -$row['settlement_price']/100) >= 0.1){
                        $row['money3'] = '未分润';
                    }else{
                        $row['money3'] = 0.00;
                    }
                }
            }else{
                $row['money3'] = '未验券';
            }
            //分润总额
            $row['money4'] = number_format(($row['price']+$row['subtract']-$row['back_money']/100-$row['settlement_price']/100)*0.72,2);
        }else{
            $row['money3'] = '无';
            $row['money4'] = '无';
        }
        //用户信息
        $user = $user_model->where('userID',$row['user_id'])->field('account,phone,nickname')->find();
        $row['user'] = $user;
        //店铺信息
        $shop = $shop_model->where('shop_id',$row['shop_id'])->field('user_id,shop_name,province_id,city_id,area_id,rate')->find();
        $province_id = $shop['province_id'];
        $city_id = $shop['city_id'];
        $area_id = $shop['area_id'];
        if ($province_id){
            $city1 = $city_model->where('cityID',$province_id)->value('name');
            if ($city_id){
                $city2 = $city_model->where('cityID',$city_id)->value('name');
                if ($area_id){
                    $city3 = $city_model->where('cityID',$area_id)->value('name');
                    $shop['city'] = $city1.'-'.$city2.'-'.$city3;
                }else{
                    $shop['city'] = $city1.'-'.$city2;
                }
            }else{
                $shop['city'] = $city1;
            }
        }
        $shop_user = $user_model->where('userID',$shop['user_id'])->field('account,phone')->find();
        $shop['account'] = $shop_user['account'];
        $shop['phone'] = $shop_user['phone'];
        //团购
        /*if($row['order_type'] == 1){
            if($row['tuan_type'] == 1 || $row['tuan_type'] == 3){
                $shop['rate'] = number_format(($row['price']-$row['settlement_price']/100-$row['back_money']/100)/$row['price']*100,0);
            }else{
                $shop['rate'] = 0;
            }
        //买单
        }else{
            $shop['rate'] = number_format(($row['price']-$row['settlement_price']/100-$row['back_money']/100)/$row['price']*100,0);
        }*/
        $row['shop'] = $shop;
        if (!$row)
            $this->error(__('No Results were found'));
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds))
        {
            if (!in_array($row[$this->dataLimitField], $adminIds))
            {
                $this->error(__('You have no permission'));
            }
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    /**
     * 变更
     * @internal
     */
    public function change()
    {
        $this->success();
    }
}
